//
//  CategoryViewController.swift
//  XiaoXiangMu1604
//
//  Created by qianfeng on 16/9/28.
//  Copyright © 2016年 SunPiaoLiang. All rights reserved.
//

import UIKit

protocol CategoryViewControllerDelegate:NSObjectProtocol{
    
    func didClickCate(cateId: String,cateName:String)
    
}
//分类的类型
public enum CategoryType: Int{
    
    case LimitFree
    
    case Reduce
    
    case Free
    
}

class CategoryViewController: LFBaseViewController {

    //类型
    var type: CategoryType?
    
    //代理属性
    weak var delegate: CategoryViewControllerDelegate?
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
  
     tbView?.frame.size.height = KScreenHeight-64

     createMyNav()
    
    }
    func createMyNav(){
        
        addBackButton()
        
        var titleStr = ""
        
        if type == .LimitFree{
            
            titleStr = "限免—分类"
            
        }else if type == .Reduce{
            
            titleStr = "降价—分类"
            
        }else if type == .Free{
            
            titleStr = "免费-分类"
            
        }
    
        addNavTitle(titleStr)
        
    }
    override func downloadData() {
        
        ProgressHUD.showOnView(view)
        
        var urlString: String? = nil
        
        if type == .LimitFree{
            
            urlString = kCategoryLimitUrl
            
        }else if type == .Reduce{
            
            urlString = kCategoryReduceUrl
            
        }else if type == .Free{
            
            urlString = kCategoryFreeUrl
            
        }
        if urlString != nil{
            
            let d = LFDownloader()
            
            d.delegate = self
            
            d.downloadWithURLString(urlString!)
            
        }
        
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
}
//MARK:LFDownloader代理
extension CategoryViewController:LFDownloaderDelegate{
    
    func downloader(downloader: LFDownloader, didFailWithError error: NSError) {
        
        ProgressHUD.hideAfterFailOnView(view)
        
        
    }
    func downloader(downloader: LFDownloader, didFinishWithData data: NSData) {
        
        let result = try! NSJSONSerialization.JSONObjectWithData(data, options: .MutableContainers)
        
        if result.isKindOfClass(NSDictionary){
            
            let dict = result as! Dictionary<String,AnyObject>
            
            let array = dict["category"] as! Array<Dictionary<String,AnyObject>>
            
            for cateDict in array{
                
                let cateId = cateDict["categoryId"]
                
                let cateIdStr = "\(cateId!)"
                
                if  cateIdStr == "0"{
                   
                    continue
                    
                }
                
                let model = CategoryModel()
                
                model.setValuesForKeysWithDictionary(cateDict)
                
                dataArray.addObject(model)
                
            }
            
            //刷新表格
            dispatch_async(dispatch_get_main_queue(), {
                
                self.tbView?.reloadData()
                
                ProgressHUD.hideAfterSuccessOnView(self.view)
                
            })
            
        }
        
    }

}

extension CategoryViewController{
    //实现创建表格的方法
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return dataArray.count
    }
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        
        return 100
    }
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        
        let cellId = "categoryCellId"
        
        var cell = tableView.dequeueReusableCellWithIdentifier(cellId) as? CategoryCell
        
        if cell == nil{
            
            cell = NSBundle.mainBundle().loadNibNamed("CategoryCell", owner:nil, options: nil).last as? CategoryCell
            
        }
        //显示数据
        let model = dataArray[indexPath.row] as! CategoryModel
        
        cell?.config(model,type: type!)
        
        return cell!
        
    }

    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        
        let model = dataArray[indexPath.row] as! CategoryModel
        
        let cateId = "\(model.categoryId!)"
        
        let cateName = MyUtil.transferCateName(model.categoryName!)
        
        delegate?.didClickCate(cateId, cateName: cateName)
        
        navigationController?.popViewControllerAnimated(true)
        
    }
    
}

